package com.zlw.netty.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

/**
 * @ClassName ChatHandler
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2020/1/18  23:22
 * @Version 1.0
 */

public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    //用于记录 管理所有客户端的channel
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext channel, TextWebSocketFrame text) throws Exception {
        //发过来的 消息在 TextWebSocketFrame 这个类中
        String context = text.text();
        System.out.println("接收到的消息 : " + context);

//        for (Channel client : clients) {
//            client.writeAndFlush("[服务器在:  ]" + LocalDateTime.now() + " 接收到消息 ,消息为 : " + context);
//        }

        clients.writeAndFlush(new TextWebSocketFrame("[服务器在:  ]" + LocalDateTime.now() + " 接收到消息 ,消息为 : " + context));

    }

    //建立链接
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //super.handlerAdded(ctx);
        Channel channel = ctx.channel();
        clients.add(channel);
    }

    //浏览器关闭了
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
//        super.handlerRemoved(ctx);
//        当触发 handlerRemoved 时 ChannelGroup 会自动移除 对应的客户端channel
//        clients.remove(ctx.channel());

        System.out.println("客户端断开 channel 对应的长 id为： " + ctx.channel().id().asLongText());
        System.out.println("客户端断开 channel 对应的短 id为： " + ctx.channel().id().asShortText());

    }
}
